(function () {
    var core = ecui,
        util = core.util,
        ui = ecui.ui,
        dom = ecui.dom;

    Object.assign(
        NS.data,
        {
            accountList: []
        }
    );
    Object.assign(
        NS.ui,
        {
            // 费用申请-新增费用按钮
            EditCostBtn: ecui.inherits(
                mao.ui.SelectEdit,
                function (el, options) {
                    mao.ui.SelectEdit.call(this, el, options);
                    this._sName = options.name;
                    this._sInvoiceType = options.invoiceType;
                },
                {
                    onchange: function (event) {
                        var cont = ecui.$('cost_cont_' + this._sNum);
                        var view = 'cost-purchase-item';['', 'cost-purchase-item', 'cost-item'][this._sInvoiceType];
                        var el = dom.create({
                            innerHTML: ecui.esr.getEngine().render('bill.' + view, { name: this._sName, item: event.item, num: this._sNum })
                        });
                        cont.appendChild(dom.last(el));
                        ecui.init(dom.last(cont));
                    },

                    /**
                     * @override
                     */
                    init: function () {
                        mao.ui.SelectEdit.prototype.init.call(this);
                        util.timer(function () {
                            delete this._oRegExp;
                        }, 10, this);
                    }
                }
            ),
            EditCostConfirmBtn: ecui.inherits(
                ui.Button,
                {
                    onclick: function () {
                        var form = document.forms.editCostForm,
                            data = {},
                            vilad = ecui.esr.parseObject(form, data),
                            layer = mao.util.getLayer(this);
                        if (vilad) {
                            console.log(data);
                            ecui.dispatchEvent(layer, 'confirm', { item: data });
                        } else {
                            ecui.tip('warn', '请完成必填项');
                        }
                    }
                }
            ),
            // 申请单提交按钮
            EditCostSubmitBtn: ecui.inherits(
                ui.Button,
                function (el, options) {
                    ui.Button.call(this, el, options);
                    this._sInvoiceType = options.invoiceType;
                    this._sOptId = options.optId;
                },
                {
                    onclick: function () {
                        this.request(
                            'data@FORM /erp-management/application/save?editBillForm',
                            function () {
                                var code = ecui.esr.getData('data_CODE');
                                if (code === 0) {
                                    var tip = util.stringFormat('{0}{1}申请单成功', '创建', this._sInvoiceType === '1' ? '采购' : '费用');
                                    ecui.tip('success', tip);
                                    history.go(-1);
                                }
                            },
                            function () {
                                return false;
                            }
                        );
                    }
                },
                ui.Submit
            ),
            // 往来单位选择
            ContactUnitSelectEdit: ecui.inherits(
                mao.ui.SelectEdit,
                {
                    onchange: function (event) {
                        this.setSelected(event);
                        this.getAccountList();
                    },
                    getAccountList: function () {
                        ecui.esr.request(
                            'accountList@GET /erp-management/account/list/' + this.getFormValue(),
                            function () {
                                var code = ecui.esr.getData('accountList_CODE');
                                var accountList = ecui.esr.getData('accountList');
                                if (code === 0) {
                                    NS.data.accountList = accountList;
                                }
                            }.bind(this),
                            function () {}
                        );
                    },
                    onready: function () {
                        this.getAccountList();
                    }
                }
            ),

            // 选择账号按钮
            AccountSelectEdit: ecui.inherits(
                mao.ui.SelectEdit,
                function (el, options) {
                    options.weight = 9990;
                    mao.ui.SelectEdit.call(this, el, options);
                    this._sAccountUnit = options.accountUnit;
                },
                {
                    $click: function (event) {
                        var uAccountUnit = ecui.get(this._sAccountUnit);;
                        var accountUnit = uAccountUnit.getFormValue();
                        if (accountUnit) {
                            if (uAccountUnit.getName() === 'contactUnitCode') {
                                // 往来单位提交的是code，查询往来单位的账户需要用id，所以通过items遍历获取 contactUnitId
                                var _accountUnit = uAccountUnit._oItems.find(function (item) { return item.contactUnitCode === accountUnit; });
                                if (_accountUnit) {
                                    accountUnit = _accountUnit.contactUnitId;
                                }
                            }
                            ecui.esr.request(
                                'accountList@GET /erp-management/account/list/' + accountUnit,
                                function () {
                                    var code = ecui.esr.getData('accountList_CODE');
                                    var accountList = ecui.esr.getData('accountList');
                                    if (code === 0) {
                                        NS.data.accountList = accountList;
                                        this._oItems = accountList;
                                        this._oOptions.accountUnit = accountUnit;
                                        mao.ui.SelectEdit.prototype.$click.call(this, event);
                                    }
                                }.bind(this),
                                function () {}
                            );
                        } else {
                            ecui.tip('success', '请先选择往来单位或承担人');
                        }
                    }
                }
            ),

            ToAccountBtn: ecui.inherits(
                ui.Control,
                {
                    onclick: function () {
                        var href = dom.getAttribute(this.getMain(), 'href');
                        // history.go(-1);
                        util.timer(function () {
                            ecui.esr.redirect(href);
                        }, 300, this);
                    }
                }
            ),

            // 费用申请-导入费用按钮
            ImportCostBtn: ecui.inherits(
                mao.ui.SelectEdit,
                {
                    onchange: function (event) {
                        var cont = dom.first(dom.parent(this.getMain()));
                        cont.innerHTML = ecui.esr.getEngine().render('bill.costItems', { item: event.item, num: this._sNum, name: 'costDetails' })
                        ecui.init(cont);
                    }
                }
            ),

            // 报销单、对公支付、借款单申请 - 新增费用按钮
            AddCostBtn: ecui.inherits(
                mao.ui.SelectRoute,
                {
                    onchange: function (event) {
                        var el = dom.create({ innerHTML: ecui.esr.getEngine().render('bill.costItem', { item: event.item, num: this._sNum, name: 'costDetails' }) });
                        var cont = dom.first(dom.parent(this.getMain()));
                        if (this._oOptions.isCopy) {
                            cont = dom.parent(this.getParent().getMain());
                            dom.insertBefore(dom.first(el), this.getParent().getMain());
                        } else {
                            dom.children(el).forEach(function (item) {
                                cont.appendChild(item);
                            });
                        }
                        ecui.init(cont);
                    }
                }
            ),

            // 消费申请单申请-新增费用按钮
            AddCostDetailBtn: ecui.inherits(
                mao.ui.SelectRoute,
                {
                    onclick: function (event) {
                        mao.info.costDetailItem = this._oItem;
                        mao.ui.SelectRoute.prototype.onclick.call(this, event);
                    },
                    onchange: function (event) {
                        var el = dom.create({ innerHTML: ecui.esr.getEngine().render('bill.cost-item', { item: event.item, num: this._sNum, name: 'applicationCostDetails' }) });
                        var cont = dom.previous(this.getMain());
                        if (this._oOptions.isCopy) {
                            cont = dom.parent(this.getParent().getMain());
                            dom.insertBefore(dom.first(el), this.getParent().getMain());
                        } else {
                            dom.children(el).forEach(function (item) {
                                cont.appendChild(item);
                            });
                        }
                        ecui.init(cont);
                    }
                }
            ),
            // 新建报销单 - 提交按钮
            SaveBillBtn: ecui.inherits(
                ui.Button,
                function (el, options) {
                    ui.Button.call(this, el, options);
                    this._sInvoiceType = options.invoiceType;
                    this._sOptId = options.optId;
                },
                {
                    onclick: function () {
                        var forms = { '3': 'editLoanBillForm', '4': 'editReimbursementForm', '5': 'editCorporatePaymentForm' };
                        var names = { '3': '借款单', '4': '报销单', '5': '对公支付' };
                        this.request(
                            'data@FORM /erp-management/' + (this._sInvoiceType === '3' ? 'borrow' : 'expense') + '/save?' + forms[this._sInvoiceType],
                            function () {
                                var data = ecui.esr.getData('data');
                                if (data instanceof Object) {
                                    var tip = util.stringFormat('{0}{1}成功', '创建', names[this._sInvoiceType]);
                                    ecui.tip('success', tip);
                                    history.go(-1);
                                }
                            }.bind(this),
                            function (err) {
                                if (!err) {
                                    ecui.tip('warn', '请完善信息');
                                }
                                return false;
                            }
                        );
                    }
                },
                ui.Submit
            ),
            // 新建借款单 - 提交按钮
            EditLoanBillSubmit: ecui.inherits(
                ui.Control,
                {
                    onclick: function () {
                        this.request(
                            'data@FORM /erp-management/borrow/save?editLoanBillForm',
                            function () {
                                var data = ecui.esr.getData('data');
                                if (data instanceof Object) {
                                    ecui.tip('success', this._sOptId ? '创建借款单成功' : '新增借款单成功');
                                    history.go(-1);
                                }
                            }.bind(this),
                            function () {
                                return false;
                            }
                        );
                    }
                },
                ui.Submit
            ),
            // 评论按钮
            BillCommentSave: core.inherits(
                mao.ui.CommentSave,
                {
                    onsubmit: function () {
                        if (this._oRequest) {
                            return;
                        }
                        this._oRequest = true;
                        var data = {};
                        var form = this.getInput().form;
                        ecui.esr.parseObject(form, data);
                        ecui.esr.setData('commentParam', data);
                        if (this.action === '7') {
                            // 评论
                            ecui.esr.request(
                                'data@JSON /erp-management/invoice/comment?${commentParam}',
                                function () {
                                    this._oRequest = false;
                                    var data = ecui.esr.getData('data');
                                    if (data instanceof Object) {
                                        ecui.tip('warn', '评论成功');
                                        var route = ecui.esr.findRoute(this.getMain());
                                        delete route.CACHE;
                                        ecui.esr.reload();
                                    }
                                }.bind(this),
                                function () {
                                    this._oRequest = false;
                                }.bind(this)
                            );
                        }
                    }
                }
            ),
            /**
             * 操作按钮控件。
             * 筛选框动态的响应用户的输入并提供选择，用户不输入时 filter 表现与普通的输入框相同。
             * options 属性：
             * bType   业务类型，1：合同；2：订单；3：票务；4：结算单 5：厂牌结算单
             * cType   操作类型，-1：删除，0：撤销，1：提交，2：驳回，3：通过，4：中止
             * tip     操作玩提示信息
             * @control
             */
            ApprovalBillSubmitBtn: core.inherits(
                ui.Button,
                function (el, options) {
                    ui.Button.call(this, el, options);
                    this._sAuditStatus = options.auditStatus;
                    this._sTip = options.tip;
                },
                {
                    onkeydown: function (event) {
                        if (event.which === 13) {
                            util.timer(function () {
                                // ecui.dispatchEvent(this, 'blur');
                                core.setFocused();
                            }, 0, this);
                            ecui.dispatchEvent(this, 'submit');
                        }
                    },
                    onclick: function (event) {
                        ecui.dispatchEvent(this, 'submit');
                    },
                    onsubmit: function () {
                        var form = this.getForm(),
                            elements = form.elements,
                            text = ['', '', '驳回', '通过'];

                        elements.auditStatus.value = this._sAuditStatus;
                        ecui.confirm(
                            '是否' + text[this._sAuditStatus],
                            function () {
                                this.request(
                                    'data@FORM /erp-management/audit/operate?' + form.name,
                                    function () {
                                        var code = ecui.esr.getData('data_CODE');
                                        if (code === 0) {
                                            ecui.tip('warn', this._sTip);
                                            this.afterActionRequest();
                                        }
                                    }.bind(this),
                                    function () {
                                        return false;
                                    }.bind(this)
                                );
                            }.bind(this)
                        );
                    },
                    afterActionRequest: function () {
                        // history.go(-1);
                        var route = ecui.esr.findRoute(this.getMain());
                        delete route.CACHE;
                        ecui.esr.reload();
                    }
                },
                ui.Submit
            ),
            /**
             * 采购申请单价、数据、金额输入控件。
             */
            PurchasePriceNumber: ecui.inherits(
                ui.Number,
                {
                    clearTimer: util.blank,
                    oninput: function () {
                        this.clearTimer();
                        this.clearTimer = util.timer(function () {
                            this.calculateCost();
                        }, 300, this);
                    },
                    calculateCost: function () {
                        var name = this.getName();
                        var unitPrice = name === 'amount' ? dom.children(dom.previous(this.getParent().getMain()))[1].getControl() : this;
                        var amount = dom.children(dom.next(unitPrice.getParent().getMain()))[1].getControl();
                        var sumPrice = dom.children(dom.next(amount.getParent().getMain()))[1].getControl()

                        sumPrice.setValue(mao.util.toFixed(+unitPrice.getValue() * +amount.getValue()) || 0);
                    }
                }
            )
        }
    );
    Object.assign(
        NS.ui,
        {
            /**
             * 财务审批操作按钮
             * options 属性：
             * bType   业务类型，1：合同；2：订单；3：票务；4：结算单 5：厂牌结算单
             * cType   操作类型，-1：删除，0：撤销，1：提交，2：驳回，3：通过，4：中止
             * tip     操作玩提示信息
             * @control
             */
            BillCommentSubmitBtn: core.inherits(
                NS.ui.ApprovalBillSubmitBtn,
                {
                    onsubmit: function () {
                        var form = this.getForm(),
                            elements = form.elements,
                            text = ['', '', '驳回', '通过'];

                        elements.auditStatus.value = this._sAuditStatus;
                        ecui.confirm(
                            '是否' + text[this._sAuditStatus],
                            function () {
                                this.request(
                                    'data@FORM /erp-finance/audit/operate?' + form.name,
                                    function () {
                                        var code = ecui.esr.getData('data_CODE');
                                        if (code === 0) {
                                            ecui.tip('warn', this._sTip);
                                            this.afterActionRequest();
                                        }
                                    }.bind(this),
                                    function () {
                                        return false;
                                    }.bind(this)
                                );
                            }.bind(this)
                        );
                    }
                }
            )
        }
    )
}());